import { Button, Checkbox, Input, InputNumber, Select, Table } from "antd";
import { randomStr } from "@/lib/utils/random";
import type { IDevice } from "@/lib/types";

export type Monitor = IDevice["monitors"][number] & {
  _id: string;
};

type CheckPointsProps = {
  value?: Monitor[];
  onChange?: (value: Monitor[]) => void;
};
const NewItemId = randomStr(16);
export default function Monitors(props: CheckPointsProps) {
  const { value = [], onChange } = props;

  function handleAdd() {
    const item: Monitor = {
      _id: randomStr(),
      id: value.length + 1,
      name: "",
      protocol: "",
      address: "",
      ip: "",
      port: "",
      serialPort: "",
      baudRate: undefined, // 波特率
      dataBits: "8",
      parity: "0",
      stopBits: "1",
      rsMode: undefined, // 串口类型
      pointType: "",
      multiple: "",
      unitName: "",
      dataType: "int16",
      upperLimit: undefined,
      lowerLimit: undefined,
      enabled: "0",
    };
    onChange?.([...value, item]);
  }

  function handleRemove(_id: string) {
    onChange?.(
      value
        .filter((item) => item._id !== _id)
        .map((item, index) => ({
          ...item,
          id: index + 1,
        })),
    );
  }

  function updateField(_id: string, field: string, newValue: any) {
    onChange?.(
      value.map((item) => {
        if (item._id !== _id) return item;
        const newItem = {
          ...item,
          [field]: newValue,
        };
        if (field === "protocol") {
          if (newValue === "ModbusTcp") {
            newItem.serialPort = "";
            newItem.baudRate = undefined;
            newItem.rsMode = undefined;
          } else {
            newItem.ip = "";
            newItem.port = "";
          }
        }
        return newItem;
      }),
    );
  }

  const dataSource = value;

  return (
    <div>
      <div className="mb-2">
        <Button type="primary" onClick={handleAdd}>
          添加测量点
        </Button>
      </div>
      <Table
        dataSource={dataSource}
        rowKey={(row) => row._id}
        pagination={false}
        scroll={{ x: "max-content" }}
      >
        <Table.Column
          title="序号"
          width={80}
          fixed="left"
          render={(row) => <span>{row.id}</span>}
          onCell={(row) => (row._id === NewItemId ? { colSpan: 20 } : {})}
        />
        <Table.Column
          title="测量点名称"
          width={150}
          render={(row) => (
            <Input
              value={row.name}
              onInput={(e) =>
                updateField(
                  row._id,
                  "name",
                  (e.target as HTMLInputElement).value,
                )
              }
            />
          )}
          onCell={(row) => (row._id === NewItemId ? { colSpan: 0 } : {})}
        />
        <Table.Column
          width={160}
          title="采样协议"
          render={(row) => (
            <Select
              value={row.protocol}
              options={[
                { label: "ModbusTcp", value: "ModbusTcp" },
                { label: "ModbusRtu", value: "ModbusRtu" },
              ]}
              onChange={(v) => updateField(row._id, "protocol", v)}
            />
          )}
          onCell={(row) => (row._id === NewItemId ? { colSpan: 0 } : {})}
        />
        <Table.Column
          title="采样地址"
          width={150}
          render={(row) => (
            <InputNumber
              value={row.address}
              className="w-full"
              onChange={(v) => updateField(row._id, "address", v)}
            />
          )}
          onCell={(row) => (row._id === NewItemId ? { colSpan: 0 } : {})}
        />
        <Table.Column
          title="IP"
          width={180}
          render={(row) => (
            <Input
              disabled={!row.protocol || row.protocol === "ModbusRtu"}
              value={row.ip}
              onInput={(e) =>
                updateField(row._id, "ip", (e.target as HTMLInputElement).value)
              }
            />
          )}
          onCell={(row) => (row._id === NewItemId ? { colSpan: 0 } : {})}
        />
        <Table.Column
          title="端口"
          width={100}
          render={(row) => (
            <InputNumber
              className="w-full"
              disabled={!row.protocol || row.protocol === "ModbusRtu"}
              value={row.port}
              onChange={(v) => updateField(row._id, "port", v)}
            />
          )}
          onCell={(row) => (row._id === NewItemId ? { colSpan: 0 } : {})}
        />
        <Table.Column
          title="串口号"
          width={120}
          render={(row) => (
            <Input
              disabled={!row.protocol || row.protocol === "ModbusTcp"}
              value={row.serialPort}
              onInput={(e) =>
                updateField(
                  row._id,
                  "serialPort",
                  (e.target as HTMLInputElement).value,
                )
              }
            />
          )}
          onCell={(row) => (row._id === NewItemId ? { colSpan: 0 } : {})}
        />
        <Table.Column
          title="波特率"
          width={120}
          render={(row) => (
            <InputNumber
              disabled={!row.protocol || row.protocol === "ModbusTcp"}
              value={row.baudRate}
              onChange={(v) => updateField(row._id, "baudRate", v)}
            />
          )}
          onCell={(row) => (row._id === NewItemId ? { colSpan: 0 } : {})}
        />
        <Table.Column
          title="DataBits"
          width={100}
          render={(row) => (
            <Select
              value={row.dataBits}
              disabled={!row.protocol || row.protocol === "ModbusTcp"}
              options={[
                { label: "7", value: "7" },
                { label: "8", value: "8" },
              ]}
              onChange={(v) => updateField(row._id, "dataBits", v)}
            />
          )}
          onCell={(row) => (row._id === NewItemId ? { colSpan: 0 } : {})}
        />
        <Table.Column
          title="Parity"
          width={100}
          render={(row) => (
            <Select
              value={row.parity}
              disabled={!row.protocol || row.protocol === "ModbusTcp"}
              options={[
                { label: "0", value: "0" },
                { label: "1", value: "1" },
                { label: "2", value: "2" },
                { label: "3", value: "3" },
                { label: "4", value: "4" },
              ]}
              onChange={(v) => updateField(row._id, "parity", v)}
            />
          )}
          onCell={(row) => (row._id === NewItemId ? { colSpan: 0 } : {})}
        />
        <Table.Column
          title="StopBits"
          width={100}
          render={(row) => (
            <Select
              value={row.stopBits}
              disabled={!row.protocol || row.protocol === "ModbusTcp"}
              options={[
                { label: "1", value: "1" },
                { label: "2", value: "2" },
                { label: "3", value: "3" },
              ]}
              onChange={(v) => updateField(row._id, "stopBits", v)}
            />
          )}
          onCell={(row) => (row._id === NewItemId ? { colSpan: 0 } : {})}
        />
        <Table.Column
          title="串口类型"
          width={120}
          render={(row) => (
            <Select
              disabled={!row.protocol || row.protocol === "ModbusTcp"}
              value={row.rsMode}
              options={[
                { label: "rs232", value: "rs232" },
                { label: "rs485", value: "rs485" },
              ]}
              onChange={(v) => updateField(row._id, "rsMode", v)}
            />
          )}
          onCell={(row) => (row._id === NewItemId ? { colSpan: 0 } : {})}
        />
        <Table.Column
          title="功能码"
          width={120}
          render={(row) => (
            <Select
              value={row.pointType}
              options={[
                { label: "03", value: "03" },
                { label: "04", value: "04" },
              ]}
              onChange={(v) => updateField(row._id, "pointType", v)}
            />
          )}
          onCell={(row) => (row._id === NewItemId ? { colSpan: 0 } : {})}
        />
        <Table.Column
          title="上限"
          width={120}
          render={(row) => (
            <InputNumber
              value={row.upperLimit}
              onChange={(v) => updateField(row._id, "upperLimit", v)}
            />
          )}
          onCell={(row) => (row._id === NewItemId ? { colSpan: 0 } : {})}
        />
        <Table.Column
          title="下限"
          width={120}
          render={(row) => (
            <InputNumber
              value={row.lowerLimit}
              onChange={(v) => updateField(row._id, "lowerLimit", v)}
            />
          )}
          onCell={(row) => (row._id === NewItemId ? { colSpan: 0 } : {})}
        />
        <Table.Column
          title="倍数"
          width={120}
          render={(row) => (
            <Input
              value={row.multiple}
              onInput={(e) =>
                updateField(
                  row._id,
                  "multiple",
                  (e.target as HTMLInputElement).value,
                )
              }
            />
          )}
          onCell={(row) => (row._id === NewItemId ? { colSpan: 0 } : {})}
        />
        <Table.Column
          title="单位"
          width={120}
          render={(row) => (
            <Input
              value={row.unitName}
              onInput={(e) =>
                updateField(
                  row._id,
                  "unitName",
                  (e.target as HTMLInputElement).value,
                )
              }
            />
          )}
          onCell={(row) => (row._id === NewItemId ? { colSpan: 0 } : {})}
        />
        <Table.Column
          title="数据类型"
          width={120}
          render={(row) => (
            <Select
              value={row.dataType}
              options={[
                { label: "int16", value: "int16" },
                { label: "int32", value: "int32" },
                { label: "unit32", value: "unit32" },
                { label: "f32", value: "f32" },
              ]}
              onChange={(v) => updateField(row._id, "dataType", v)}
            />
          )}
          onCell={(row) => (row._id === NewItemId ? { colSpan: 0 } : {})}
        />
        <Table.Column
          title="开启"
          width={80}
          render={(row) => (
            <Checkbox
              checked={row.enabled === "1"}
              onChange={(e) =>
                updateField(row._id, "enabled", e.target.checked ? "1" : "0")
              }
            />
          )}
          onCell={(row) => (row._id === NewItemId ? { colSpan: 0 } : {})}
        />
        <Table.Column
          title="操作"
          width={100}
          fixed="right"
          render={(row) => (
            <Button onClick={() => handleRemove(row._id)}>删除</Button>
          )}
          onCell={(row) => (row._id === NewItemId ? { colSpan: 0 } : {})}
        />
      </Table>
    </div>
  );
}
